package cc.rengu.igas.smps.core.packswitch;

import cc.rengu.igas.smps.common.constant.SmpsTreeNodeConstant;
import cc.rengu.igas.smps.common.enums.RespCodeEnum;
import cc.rengu.jradp.packetswitch.IncomingPackSwitchImpl;
import cc.rengu.jradp.packetswitch.OutgoingPackSwitchImpl;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.dao.SysParamMapper;
import cc.rengu.oltp.service.common.dao.impl.SysParamMapperImpl;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.MD5Util;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wukefan
 * @version 1.0.0
 * @date 2020/7/31 9:38
 */
public class CompMhcntPushClientPackSwitch implements IncomingPackSwitchImpl, OutgoingPackSwitchImpl {
    RgLogger rglog = RgLog.getLogger(this.getClass().getName());

    @Override
    public byte[] beforeInComPackSwitch(byte[] bytes) throws Exception {
        return bytes;
    }

    @Override
    public int afterInComPackSwitch() throws Exception {
        return 0;
    }

    @Override
    public int beforeOutgoPackSwitch() throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID), "COMPMCHNTPUSHTXNSIGN", xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TXN_NUM));
        if (sysParam != null && !StringUtil.isEmptyOrNull(sysParam.getParamValue()) && "Y".equals(sysParam.getParamStatus())) {
            xmlTreeUtil.setXmlTreeStringValue("txn_sign_param", sysParam.getParamValue());
        }

        return 0;
    }

    @Override
    public byte[] afterOutgoPackSwitch(byte[] bytes) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sendBuf = new String(bytes);
        rglog.debug("sendBuf = <{}>", sendBuf);
        String signKey = xmlTreeUtil.getXmlTreeStringValue(SmpsTreeNodeConstant.SIGN_KEY);
        String signParam = xmlTreeUtil.getXmlTreeStringValue("txn_sign_param");
        String signBlock = null;
        if (!StringUtil.isEmptyOrNull(signParam)) {
            signBlock = generateSignBlockString(sendBuf, signParam, signKey);
        }
        if (null == signBlock) {
            rglog.error("生成加签Block失败!");
            throw new BizException(RespCodeEnum.GENERATE_SIGN_BLOCK_ERROR.getRespCode(), RespCodeEnum.GENERATE_SIGN_BLOCK_ERROR.getRespDesc());
        }
        rglog.debug("签名:<{}>", signBlock);
        /**添加sign字符串到报文中*/
        String jsonAfter = jsonStringAppendSign(sendBuf, signBlock);
        //
        Map<String, String> reqMap = new HashMap<String, String>();
        reqMap.put("error", "S000A000");
        reqMap.put("error_description", "success");
        reqMap.put("nonce_str", "success");
        reqMap.put("data", jsonAfter);
        xmlTreeUtil.setXmlTreeStringValue("_MESSAGEHEAD/http/Content-Type", "text/plain;charset=utf-8");
        xmlTreeUtil.setXmlTreeStringValue("_MESSAGEHEAD/http/ArgList", "Content-Type");
        return JSONObject.toJSONString(reqMap).getBytes();
    }

    private String generateSignBlockString(String jsonString, String signParam, String signKey) {
        RgLogger rglog = RgLog.getLogger(this.getClass().getName());
        try {
            if (null != jsonString && 0 != jsonString.trim().length()) {
                //TODO：需配置参数表信息  最后一个为sign_key
                JSONObject jsonObject = JSON.parseObject(jsonString);
                jsonObject.put("sign_key", signKey);
                StringBuffer strBuffer = new StringBuffer();
                String[] signData = signParam.split("\\|");
                if (signData != null && signData.length != 0) {
                    for (int i = 0; i < signData.length; i++) {
                        if (!StringUtil.isEmptyOrNull(jsonObject.getString(signData[i]))) {
                            rglog.info("key = <{}>,value = <{}>", signData[i], jsonObject.getString(signData[i]));
                            strBuffer.append(signData[i] + "=" + jsonObject.getString(signData[i]) + "&");
                        }
                    }
                    return MD5Util.MD5Encode(strBuffer.substring(0, strBuffer.length() - 1).toString()).toUpperCase();
                }
            }
        } catch (Exception e) {
            rglog.error("生成sign签名失败");
            rglog.error("系统异常!");
            return null;
        }
        return null;
    }

    private String jsonStringAppendSign(String jsonString, String sign) {
        RgLogger rglog = RgLog.getLogger(this.getClass().getName());
        try {
            if (null != jsonString && 0 != jsonString.trim().length()) {
                Map maps = (Map) JSON.parse(jsonString);
                maps.put("sign", sign);
                return Base64.encodeBase64String(JSON.toJSONString(maps).getBytes());
            }
        } catch (Exception e) {
            rglog.error("添加sign签名失败");
            rglog.error("系统异常!");
            return null;
        }
        return null;
    }
}
